package com.xk857.article.mapper.provider;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xk857.article.req.ArticleListREQ;
import com.xk857.entities.Article;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author CV大魔王
 * @Description 文章动态SQL
 * @date 2021/2/22 21:57
 */
public class ArticleProvider {

    /**
     * 新增文章知识点中间表数据 动态添加多个知识点
     *
     * @param articleId 文章id
     * @param labelIds  知识点id
     * @return sql语句
     */
    public String saveArticleLabel(String articleId, List<String> labelIds) {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO xk857_article_label(id, article_id, label_id) VALUES ");
        for (int i = 0; i < labelIds.size(); i++) {
            if (i == labelIds.size() - 1) {
                sql.append(" (").append(IdWorker.getId()).append(", ").append(articleId).append(", ").append(labelIds.get(i)).append(") ");
            } else {
                sql.append(" (").append(IdWorker.getId()).append(", ").append(articleId).append(", ").append(labelIds.get(i)).append("), ");
            }
        }
        return sql.toString();
    }


    /**
     * 通过分类id或标签id查询文章列表
     *
     * @param page 分页数据
     * @param req  查询条件
     * @return sql语句
     */
    public String findListByLabelIdOrCategoryId(IPage<Article> page, @Param("req") ArticleListREQ req) {
        StringBuilder sql = new StringBuilder();
//        sql.append("SELECT DISTINCT xa3.* FROM xk857_label xl JOIN xk857_article_label xal on xl.id = xal.label_id JOIN xk857_article xa3 on xal.article_id = xa3.id WHERE xa3.ispublic = 1 AND xa3.`status` = 2");
        sql.append("SELECT DISTINCT xa3.id, xa3.user_id, xa3.nick_name, xa3.user_image, xa3.title, xa3.summary, xa3.image_url,  xa3.view_count, xa3.thumhup, xa3.status, xa3.ispublic, xa3.create_date, xa3.update_date FROM xk857_label xl JOIN xk857_article_label xal on xl.id = xal.label_id JOIN xk857_article xa3 on xal.article_id = xa3.id WHERE xa3.ispublic = 1 AND xa3.`status` = 2");
        if (StringUtils.isNotEmpty(req.getLabelId())) {
            sql.append(" AND xl.id = ").append(req.getLabelId());
        }
        if (StringUtils.isNotEmpty(req.getCategoryId())) {
            sql.append(" AND xl.category_id = ").append("'" + req.getCategoryId() + "'");
        }
        if (StringUtils.isNotEmpty(req.getTitle())) {
            sql.append(" AND (xa3.title like '%").append(req.getTitle()).append("%' or xa3.summary like '%").append(req.getTitle()).append("%') ");
        }
        if (StringUtils.isNotEmpty(req.getTitle())) {
            sql.append(" AND (xa3.title like '%").append(req.getTitle()).append("%' or xa3.summary like '%").append(req.getTitle()).append("%') ");
        }
        sql.append(" ORDER BY xa3.update_date DESC ");
        return sql.toString();
    }
}
